package logic

import (
	"context"
	"errors"
	"fmt"
	"furni-max/funcirpc/funcirpc"
	"furni-max/funcirpc/internal/svc"
	"furni-max/models/mysql"
	"github.com/zeromicro/go-zero/core/logx"
)

type FuncAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFuncAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FuncAddLogic {
	return &FuncAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FuncAddLogic) FuncAdd(in *funcirpc.FuncAddRequest) (*funcirpc.FuncAddResponse, error) {
	// todo: add your logic here and delete this line
	begin := mysql.DB.Debug().Begin()
	class := mysql.Class{
		Name: in.ClassName,
	}
	err := begin.Where("name = ?", in.ClassName).FirstOrCreate(&class).Error

	if err != nil {
		begin.Rollback()
		return nil, errors.New("分类添加失败")
	}
	brand := mysql.Brand{
		Name: in.BrandName,
	}
	err = begin.Where("name =?", in.BrandName).FirstOrCreate(&brand).Error
	if err != nil {
		begin.Rollback()
		return nil, errors.New("品牌添加失败")
	}
	tool := mysql.Tool{
		Name:    in.Name,
		Price:   float64(in.Price),
		Stock:   in.Stock,
		Image:   in.Image,
		Info:    in.Info,
		ClassId: int64(class.ID),
		BrandId: int64(brand.ID),
	}
	err = mysql.DB.Debug().Create(&tool).Error

	if err != nil {
		begin.Rollback()
		return nil, fmt.Errorf("家具添加失败")
	}
	begin.Commit()
	return &funcirpc.FuncAddResponse{
		ToolId: int64(tool.ID),
	}, nil

}
